package com.dh.convert.jackson;

import java.text.SimpleDateFormat;
import com.dh.convert.exception.ConvertValueException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;

public class JSON {
	public final static ObjectMapper json = new ObjectMapper();

	static {
    	json.setNodeFactory(JsonNodeFactory.withExactBigDecimals(true));
    	json.configure(MapperFeature.USE_ANNOTATIONS, false);
    	json.configure(Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    	json.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    	json.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    	json.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    	json.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    	json.setSerializationInclusion(Include.NON_NULL);
    	json.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

	public static String toJsonString(Object o) {
		try {
			return json.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			throw new ConvertValueException(e);
		}
	}

	public static <T> T toBean(String s, Class<T> valueType) {
		try {
			return json.readValue(s, valueType);
		} catch (Exception e) {
			throw new ConvertValueException(e);
		}
	}

	public static <T> T treeToValue(TreeNode n, Class<T> valueType) {
		try {
			return json.treeToValue(n, valueType);
		} catch (Exception e) {
			throw new ConvertValueException(e);
		}
	}

	public static JsonNode readTree(String content) {
		try {
			return json.readTree(content);
		} catch (Exception e) {
			throw new ConvertValueException(e);
		}
	}

	public static JsonNode valueToTree(Object o) {
		try {
			return json.valueToTree(o);
		} catch (Exception e) {
			throw new ConvertValueException(e);
		}
	}
}
